﻿using AutoMapper;
using MediatR;
using PublicClass.Entity;
using S.Eartag.Domain;
using S.Eartag.Domain.Model;
using S.Eartag.Infrastructure.Interface;
using S.Eartag.Read.API.Application.Command.LamBingCommand;
using System.Linq.Expressions;

namespace S.Eartag.Read.API.Application.CommandHandlers.LamBingCommandHandler
{
    public class LamBingGetCommandHandler : IRequestHandler<LamBingGetCommand, PageInfoS<LamBing>>
    {
        private readonly ILamBingRepository lamBingRepository;
        private readonly IMapper mapper;

        public LamBingGetCommandHandler(ILamBingRepository lamBingRepository, IMapper mapper)
        {
            this.lamBingRepository = lamBingRepository;
            this.mapper = mapper;
        }

        public async Task<PageInfoS<LamBing>> Handle(LamBingGetCommand request, CancellationToken cancellationToken)
        {
            var list = lamBingRepository.All().Result.Where(x => !x.IsDel).AsQueryable();
            if (!string.IsNullOrEmpty(request.earnumber))
            {
                list = list.Where(x => x.EarNumber.Contains(request.earnumber));
            }

            if (request.breed != 0)
            {
                list = list.Where(x => x.Breed == request.breed);
            }
            if (request.statebirth != 0)
            {
                list = list.Where(x => x.StateBirth == request.statebirth);
            }
            if (request.usecondition != 0)
            {
                list = list.Where(x => x.UseCondition == request.usecondition);
            }

            int totalCount = list.Count();
            int pageCount = (int)Math.Ceiling((totalCount * 1.0) / request.psize);
            list = list.OrderByDescending(x=>x.Id).Skip((request.pindex - 1) * request.psize).Take(request.psize);
            return new  PageInfoS<LamBing>()
            {
                list = list.ToList(),
                pageCount = pageCount,
                totalCount = totalCount,
            };
        }
    }
}
